﻿using System;
using System.Net;
using SomeKit.Http;
using SomeKit.Serialization;

namespace SomeKit.TypeSafe.BasicAuthentication
{
    public static partial class ClientHelper
    {
        #region Append basic authentication.
        /// <summary>
        /// Appends basic authentication to the additional headers being set by <paramref name="headerHandler"/>
        /// </summary>
        /// <param name="headerHandler">The basic header handler being applied after basic authentication has been applied</param>
        /// <param name="userName">The username part of the credential.</param>
        /// <param name="password">The password of the credential.</param>
        /// <returns>The Base64 encoded credentials.</returns>
        private static Action<HttpWebRequest> AppendBasicAuthentication(this Action<HttpWebRequest> headerHandler, string userName, string password)
        {
            return request =>
            {
                if (headerHandler != null)
                    headerHandler(request);
                request.SetBasicAuthentication(userName, password);
            };
        }

        /// <summary>
        /// Creates a delegate, that sets content- and accept type to application/xml and then appends basic authentication credentials.
        /// </summary>
        /// <param name="userName">The username part of the credential.</param>
        /// <param name="password">The password of the credential.</param>
        /// <returns>The delegate.</returns>
        private static Action<HttpWebRequest> AppendXmlAndBasicAuthentication(this Action<HttpWebRequest> headerHandler, string userName, string password)
        {
            return request =>
            {
                request.SetAcceptType(HttpHelper.SerializationType.XML);
                request.SetContentType(HttpHelper.SerializationType.XML);
                request.SetBasicAuthentication(userName, password);
            };
        }
        /// <summary>
        /// Creates a delegate, that sets content- and accept type to application/json and then appends basic authentication credentials.
        /// </summary>
        /// <param name="userName">The username part of the credential.</param>
        /// <param name="password">The password of the credential.</param>
        /// <returns>The delegate.</returns>
        private static Action<HttpWebRequest> AppendJsonAndBasicAuthentication(this Action<HttpWebRequest> headerHandler, string userName, string password)
        {
            return request =>
            {
                request.SetAcceptType(HttpHelper.SerializationType.JSON);
                request.SetContentType(HttpHelper.SerializationType.JSON);
                request.SetBasicAuthentication(userName, password);
            };
        }
        #endregion
    }
}
